package com.core.dao.jdbcmysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class JdbcBase {

    public static String User = "tomcat";
    public static String Pwd = "123456";
    public static String Driver = "com.mysql.cj.jdbc.Driver";
    private static String Url = "jdbc:mysql://58.250.17.31:3036/ljsw_tomcat_project_01?characterEncoding=utf8";
    private static Map<String,Connection> pool = new ConcurrentHashMap<>();

    public Connection getConnection() throws Exception {
        Class.forName(Driver);
        String name = Thread.currentThread().getName();
        gc();
        if(pool.containsKey(name)){
            return  pool.get(name);
        }else {
            Connection con =  DriverManager.getConnection(Url, User, Pwd);
            pool.put(name,con);
            return con;
        }
    }

   static void gc()throws Exception{
       List<String> keys = new ArrayList<>();
        for(String key:pool.keySet()){
           if( pool.get(key).isClosed()){
               keys.add(key);
           }
        }
        for(String key : keys){
            pool.remove(key);
        }
   }
}
